Skip to content

Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for bf16(xN) and i1xN #140763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

sayantn
Copy link
Contributor

@sayantn sayantn commented May 7, 2025

This PR changes how LLVM intrinsics are codegen

Explanation of the changes

Current procedure

This is the same for all functions, LLVM intrinsics are not treated specially

  • We get the LLVM Type of a function simply using the argument types. For example, the following function
    #[link_name = "llvm.sqrt.f32"]
    fn sqrtf32(a: f32) -> f32;
    will have LLVM type simply f32 (f32) due to the Rust signature

Pros

  • Simpler to implement, no extra complexity involved due to LLVM intrinsics

Cons

  • LLVM intrinsics have a well-defined signature, completely defined by their name (and if it is overloaded, the type parameters). So, this process of converting Rust signatures to LLVM signatures may not work, for example the following code generates LLVM IR without any problem
    #[link_name = "llvm.sqrt.f32"]
    fn sqrtf32(a: i32) -> f32;
    but the generated LLVM IR is invalid, because it has wrong signature for the intrinsic (Godbolt, adding -Zverify-llvm-ir to it will fail compilation). I would expect this code to not compile at all instead of generating invalid IR.
  • LLVM intrinsics that have types in their signature that can't be accessed from Rust (notable examples are the AMX intrinsics that have the x86amx type, and (almost) all intrinsics that have vectors of i1 types) can't be linked to at all. This is a (major?) roadblock in the AMX and AVX512 support in stdarch.
  • If code uses an non-existing LLVM intrinsic, even -Zverify-llvm-ir won't complain. Eventually it will error out due to the non-existing function (courtesy of the linker). I don't think this is a behavior we want.

What this PR does

  • When linking to non-overloaded intrinsics, we use the function LLVMIntrinsicGetType to directly get the function type of the intrinsic from LLVM.
  • We then use this LLVM definition to verify the Rust signature, and emit a proper error if it doesn't match, instead of silently emitting invalid IR.

This PR only focuses on non-overloaded intrinsics, overloaded can be done in a future PR

Regardless, the undermentioned functionalities work for all intrinsics

  • If we can't find the intrinsic, we check if it has been AutoUpgraded by LLVM. If not, that means it is an invalid intrinsic, and we error out.
  • (Yet to be implemented) Don't allow intrinsics from other archs to be declared, e.g. error out if an AArch64 intrinsic is declared when we are compiling for x86

Pros

  • It is now not possible (or at least, it would require significantly more leaps and bounds) to introduce invalid IR using non-overloaded LLVM intrinsics.

  • As we are now doing the matching of Rust signatures to LLVM intrinsics ourselves, we can now add bypasses to enable linking to such non-Rust types (e.g. matching 8192-bit vectors to x86amx and injecting llvm.x86.cast.vector.to.tile and llvm.x86.cast.tile.to.vectors in callsite)

    Also, small clarification, I don't intend for these bypasses to be permanent (at least the bf16 and i1 ones, the x86amx bypass seems inevitable). A better approach will be introducing a bf16 type in Rust, and allowing repr(simd) with bools to get Rust-native i1xNs. These are meant to be short-time, as I mentioned, "bypass"es. They shouldn't cause any major breakage even if removed, as link_llvm_intrinsics is perma-unstable.

    This PR adds bypasses for bf16 (via i16), bf16xN (via i16xN), i1xN (via iM, where M is the smallest power of 2 s.t. M >= N, unless N <= 4, where we use M = 8). This will unblock AVX512-VP2INTERSECT and a lot of bf16 intrinsics in stdarch. This PR also automatically destructures structs if the types don't exactly match (this is required for us to start emitting hard errors on mismmatches).

Cons

  • This only works for non-overloaded intrinsics (at least for now). Improving this to work with overloaded intrinsics too will involve significantly more work.

Possible ways to extend this to overloaded intrinsics (future)

Parse the mangled intrinsic name to get the type parameters

LLVM has a stable mangling of intrinsic names with type parameters (in LLVMIntrinsicCopyOverloadedName2), so we can parse the name to get the type parameters, and then just do the same thing.

Pros

  • For most intrinsics, this will work perfectly, and is a easy way to do this.

Cons

  • The LLVM mangling is not perfectly reversible. When we have TargetExt types or identified structs, their name is a part of the mangling, making it impossible to reverse. Even more complexities arise when there are unnamed identified structs, as LLVM adds more mangling to the names.

Use the IITDescriptor table and the Rust function signature

We can use the base name to get the IITDescriptors of the corresponding intrinsic, and then manually implement the matching logic based on the Rust signature.

Pros

  • Doesn't have the above mentioned limitation of the parsing approach, has correct behavior even when there are identified structs and TargetExt types. Also, fun fact, Rust exports all struct types as literal structs (unless it is emitting LLVM IR, then it always uses named identified structs, with mangled names)

Cons

  • Doesn't actually use the type parameters in the name, only uses the base name and the Rust signature to get the llvm signature (although we can check that it is the correct name). It means there would be no way to (for example) link against llvm.sqrt.bf16 until we have bf16 types in Rust. Because if we are using u16s (or any other type) as bf16s, then the matcher will deduce that the signature is u16 (u16) not bf16 (bf16) (which would lead to an error because u16 is not a valid type parameter for llvm.sqrt), even though the intended type parameter is specified in the name.
  • Much more complex, and hard to maintain as LLVM gets new IITDescriptorKinds

These 2 approaches might give different results for same function. Let's take

#[link_name = "llvm.is.constant.bf16"]
fn foo(a: u16) -> bool

The name-based approach will decide that the type parameter is bf16, and the LLVM signature is i1 (bf16) and will inject some bitcasts at callsite.
The IITDescriptor-based approach will decide that the LLVM signature is i1 (u16), and will see that the name given doesn't match the expected name (llvm.is.constant.u16), and will error out.

Other things that this PR does

  • disables all ABI checks only for the unadjusted ABI to facilitate the implementation of AMX (otherwise passing 8192-bit vectors to the intrinsic won't be allowed). This is "safe" because this ABI is only used to link to LLVM intrinsics, and passing vectors of any lengths to LLVM intrinsics is fine, because they don't exist in machine level. (moved to another PR)
  • Removes unnecessary bitcasts in cg_llvm/builder::check_call (now renamed as cast_arguments due to its new counterpart cast_return). This was old code from when Rust used to pass non-erased lifetimes to LLVM.

Reviews are welcome, as this is my first time actually contributing to rustc

After CI is green, we would need a try build and a rustc-perf run.

@rustbot label T-compiler A-codegen A-LLVM
r? codegen

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. O-x86_64 Target: x86-64 processors (like x86_64-*) (also known as amd64 and x64) labels May 7, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 8, 2025

Some changes occurred in compiler/rustc_codegen_ssa

cc @WaffleLapkin

@sayantn

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rustbot
Copy link
Collaborator

rustbot commented May 8, 2025

Some changes occurred in compiler/rustc_codegen_gcc

cc @antoyo, @GuillaumeGomez

@rust-log-analyzer

This comment has been minimized.

@sayantn sayantn changed the title Add auto-bitcasts from/to x86amx and i32x256 for AMX intrinsics Add auto-bitcasts from/to x86amx for i32x256 for AMX intrinsics May 8, 2025
@sayantn sayantn changed the title Add auto-bitcasts from/to x86amx for i32x256 for AMX intrinsics Add auto-bitcasts between x86amx and i32x256 for AMX intrinsics May 8, 2025
@sayantn

This comment has been minimized.

@dianqk
Copy link
Member

dianqk commented May 9, 2025

I think you can use LLVMGetIntrinsicDeclaration, LLVMGetIntrinsicDeclaration or some functions in Intrinsic.h in declare_raw_fn, as a reference: https://github.com/llvm/llvm-project/blob/d35ad58859c97521edab7b2eddfa9fe6838b9a5e/llvm/lib/AsmParser/LLParser.cpp#L330-L335.

@sayantn
Copy link
Contributor Author

sayantn commented May 9, 2025

That can be used to improve performance, I am not really focusing on performance in this PR. I want to currently emphasize the correctness of the codegen.

@sayantn
Copy link
Contributor Author

sayantn commented May 9, 2025

Oh wait, I probably misunderstood your comment, you meant using the llvm declaration by itself. Yeah, that would be better, thanks for the info. I will update the impl when I get the chance

@dianqk
Copy link
Member

dianqk commented May 15, 2025

Oh wait, I probably misunderstood your comment, you meant using the llvm declaration by itself. Yeah, that would be better, thanks for the info. I will update the impl when I get the chance

I think you can just focus on non-overloaded functions for this PR. Overloaded functions and type checking that checking Rust function signatures using LLVM defined can be subsequent PRs.

@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels May 15, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 15, 2025

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@sayantn

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@sayantn sayantn marked this pull request as draft May 19, 2025 07:23
@nikic
Copy link
Contributor

nikic commented May 19, 2025

@sayantn Taking the address of an intrinsic is invalid LLVM IR.

@nikic
Copy link
Contributor

nikic commented May 27, 2025

Upon testing with this I have discovered quite a few stdarch intrinsics that use invalid LLVM intrinsics (I don't know how the CI suite didn't catch this), and some that generate invalid IR. So I would send a stdarch PR too

Do you have some examples? Most likely the intrinsics aren't invalid, just old. Intrinsics change over time and support auto-upgrade.

@sayantn
Copy link
Contributor Author

sayantn commented May 27, 2025

I am testing for upgrades with upgradeIntrinsicFunction, these are not even upgradable. The ones I have found are

  • llvm.s390.vupl{b,f}w
  • llvm.ppc.altivec.s{l,r}{l,o,v}
  • llvm.ppc.altivec.sra{b,h,w}

Along with that I have found that 2 intrinsics use wrong parameters. The 2nd parameter for llvm.loongarch.lddir.d and llvm.loongarch.ldpte.d should be immediate (i.e. const generic in Rust), but they were written as simple arguments, which lead to -Zverify-llvm-ir failing (even in nightly).

Also, there are (invalid) uses of simd_{or,and,xor} on floating point types in the implementation of vec_sel in s390x.

I have also found a lot of upgradable intrinsics (mainly in x86 and arm), but I am not bothered about them.

These were not detected before due to #[inline] and generics. The codegen backend doesn't get invoked if an #[inline] function is not used (even if pub) or if it is not monomorphized (which is typically achieved by tests, but not all archs have full test coverage). I believe this can be prevented in future by

  • Having assert_instr for all intrinsics, even assert_instr(nop) works (it will not check for any particular instruction, but will still compile the function
  • For const generic intrinsics, take care to instantiate at least 1 monomorphization for every distinct LLVM intrinsic it is using (which is often achieved by assert_instr)
  • Having -Zverify-llvm-ir in the test script. It will not save us from invalid intrinsics (for some reason, it doesn't complain if I link against a non-existing intrinsic), but will take care of other sources of invalid IR.

cc @Amanieu

@rustbot rustbot added the F-autodiff `#![feature(autodiff)]` label May 28, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 28, 2025

Some changes occurred in compiler/rustc_codegen_llvm/src/builder/autodiff.rs

cc @ZuseZ4

@rust-log-analyzer

This comment has been minimized.

@rustbot rustbot added the A-run-make Area: port run-make Makefiles to rmake.rs label May 28, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 28, 2025

This PR modifies run-make tests.

cc @jieyouxu

@sayantn
Copy link
Contributor Author

sayantn commented May 28, 2025

There was an invalid intrinsic in run-make/simd-ffi/simd.rs 🙂. The problem with invalid intrinsics (as opposed to invalid signatures of valid intrinsics) is that they silently compile, even -Zverify-llvm-ir doesn't complain. They just generate a call to an unknown function in asm, which will eventually fail linking, but most tests don't link at all.

@sayantn
Copy link
Contributor Author

sayantn commented May 28, 2025

After CI is green, I think we should do a try build and an rustc-perf run, because this modifies quite a bit in the codegen of rust and llvm intrinsics, which might have some performance footprint (I am especially concerned about rust-intrinsics, I got rid of the signature table on grounds that we don't need to do it anymore, but we might still need it as a cache)

@sayantn sayantn changed the title Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for x86amx Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for x86amx, bf16(xN) and i1xN May 29, 2025
@rust-log-analyzer

This comment has been minimized.

@sayantn
Copy link
Contributor Author

sayantn commented May 29, 2025

Can anyone help here? IDK what's going on, in my system (x86_64-unknown-linux-gnu), I can actually see the note (I did ./x test --stage 1 tests/ui/codegen --bless, no changes)

@workingjubilee
Copy link
Member

Assuming they can stand separately, can we split up the intrinsic changes from the extern "unadjusted" changes? It really feels like we are going to want to be able to bisect these individually, unfortunately.

@sayantn
Copy link
Contributor Author

sayantn commented May 30, 2025

@workingjubilee If you mean I should separate the implementation changes of Rust intrinsics into another PR, yeah no problem, but I feel like they go with this PR. I can try separating them into clean commits, but separating them into different PRs will imo not be good. But I don't think I should separate the loosening of ABI check rules for extern "unadjusted" functions, it is required for the AMX bypass to make sense.

PS: I don't really like that we use the same term for rustc builtins and LLVM builtins, but oh well

@sayantn
Copy link
Contributor Author

sayantn commented May 30, 2025

Sorry for the repeated force pushes, I refactored my code quite a bit, and restructured the commits

 - Correct usage of invalid intrinsics in tests
@sayantn
Copy link
Contributor Author

sayantn commented May 30, 2025

As @workingjubilee suggested I will split this PR into 2, this will only add bypasses for i1xN and bf16(xN), I will open another PR for x86amx once this merges.

@sayantn sayantn changed the title Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for x86amx, bf16(xN) and i1xN Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for bf16(xN) and i1xN May 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-codegen Area: Code generation A-LLVM Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues. A-run-make Area: port run-make Makefiles to rmake.rs F-autodiff `#![feature(autodiff)]` S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants